/* eslint-disable react-hooks/exhaustive-deps */

/* eslint-disable react-native/no-inline-styles */
import dayjs from 'dayjs';
import React, {useState, memo, useEffect, useRef} from 'react';
import {
  ActivityIndicator,
  DeviceEventEmitter,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  RefreshControl,
} from 'react-native';
import AntDesign from 'react-native-vector-icons/AntDesign';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import {Agenda, LocaleConfig} from 'react-native-calendars';
import {Text, View, Colors, Image} from 'react-native-ui-lib';
import {get, post} from '@/utils/request';
import {useRequest} from 'ahooks';
import {useSelector} from 'react-redux';
import Actions from '@/components/Actions';
import {useNavigation, useIsFocused} from '@react-navigation/native';
import ReportItem from '@/components/ReportItem';

const obj = {
  1: {
    text: '未提交',
    color: '#999999',
  },
  2: {
    text: '异常',
    color: '#ff0000',
  },
  3: {
    text: '正常',
    color: '#40ADF5',
  },
};

LocaleConfig.locales['zh-Hans'] = {
  monthNames: [
    '一月',
    '二月',
    '三月',
    '四月',
    '五月',
    '六月',
    '七月',
    '八月',
    '九月',
    '十月',
    '十一月',
    '十二月',
  ],
  monthNamesShort: [
    '一',
    '二',
    '三',
    '四',
    '五',
    '六',
    '七',
    '八',
    '九',
    '十',
    '十一',
    '十二',
  ],
  dayNames: [
    '星期天',
    '星期一',
    '星期二',
    '星期三',
    '星期四',
    '星期五',
    '星期六',
  ],
  dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
  amDesignator: '上午',
  pmDesignator: '下午',
};

LocaleConfig.defaultLocale = 'zh-Hans';

function SubmitReport({route}) {
  const navigation = useNavigation();
  const isfocused = useIsFocused();
  const AgendaRef = useRef();
  const appTheme = useSelector(state => state.appTheme);
  const today = dayjs().format('YYYY-MM-DD');
  const [selected, setSelected] = useState(today);
  const [state, setState] = useState({
    items: undefined,
    markedDates: undefined,
  });
  const {run, runAsync, loading} = useRequest(
    async params => {
      let res = await get('/workTime/myList', {
        ...params,
      });
      return res?.data?.dataList ?? {};
    },
    {
      manual: true,
      onSuccess: res => {
        const items = state.items || {};
        const markItems = state.markItems || {};
        if (res?.length > 0) {
          res?.map(it => {
            const daylist =
              it?.itemWorkTimeList?.map(its => {
                return {
                  ...its,
                  day: it?.workDate,
                };
              }) ?? [];

            items[it?.workDate] = [...daylist];
            markItems[it?.workDate] = {
              marked: it?.itemWorkTimeList?.length > 0,
              dotColor: obj[it?.status]?.color,
            };
          });
          setState(s => ({
            ...s,
            items: {
              ...s.items,
              ...items,
            },
            markedDates: {
              ...s.markedDates,
              ...markItems,
            },
          }));
        }
      },
    },
  );

  const dosubmit = useRequest(post, {
    manual: true,
    onSuccess: res => {
      if (res.code === 0) {
        run({
          workDateStart: dayjs(selected).startOf('month').format('YYYY-MM-DD'),
          workDateEnd: dayjs(selected).endOf('month').format('YYYY-MM-DD'),
        });
      }
    },
  });

  const [action, setAction] = useState({
    visible: false,
    onDismiss: () => {
      setAction(s => ({
        ...s,
        visible: false,
      }));
    },
  });

  function toggleCalendar() {
    let agendaRef = AgendaRef?.current;
    if (agendaRef.state) {
      agendaRef.setScrollPadPosition(
        agendaRef.initialScrollPadPosition(),
        true,
      );
      agendaRef.setState({calendarScrollable: false});
      agendaRef.calendar?.current?.scrollToDay(
        agendaRef.state.selectedDay.clone(),
        agendaRef.calendarOffset(),
        true,
      );
    } else {
      agendaRef.setScrollPadPosition(0, true);
      agendaRef.enableCalendarScrolling();
    }
  }
  useEffect(() => {
    if (isfocused) {
      setTimeout(() => {
        toggleCalendar();
      }, 400);
    }
  }, [isfocused]);

  useEffect(() => {
    const listen = DeviceEventEmitter.addListener(
      'refreshreport',
      async params => {
        await runAsync({
          workDateStart: dayjs(params?.workDate)
            .startOf('month')
            .format('YYYY-MM-DD'),
          workDateEnd: dayjs(params?.workDate)
            .endOf('month')
            .format('YYYY-MM-DD'),
        });
      },
    );
    return () => {
      listen.remove();
    };
  }, []);

  return (
    <View flex-1>
      <Actions action={action} setAction={setAction} />
      <View
        paddingH-18
        paddingR-12
        paddingT-12
        paddingB-8
        row
        spread
        centerV
        height={54}
        style={{gap: 12}}>
        <Text heading flex-1>
          {dayjs(selected).format('YYYY年MM月DD日')}
        </Text>
        {dayjs().valueOf() > dayjs(selected).startOf('day').valueOf() && (
          <TouchableOpacity
            style={[
              styles.items,
              {backgroundColor: Colors.colorCardBg, width: 32, height: 32},
            ]}
            onPress={() => {
              navigation.navigate('FormPage', {
                title: '添加日报',
                type: 'AddReport',
                workDate: selected,
                navigation,
              });
            }}>
            <AntDesign name="plus" size={20} />
          </TouchableOpacity>
        )}
        {state?.items?.[selected]?.length > 0 && (
          <TouchableOpacity
            style={[
              styles.items,
              {backgroundColor: Colors.colorCardBg, width: 32, height: 32},
            ]}
            onPress={async () => {
              if (loading) {
                return;
              }
              const submitlog = state?.items?.[selected] ?? [];
              const submitarr = submitlog?.filter(it => {
                const cansubmit = [1, 3].includes(it?.status) || !it?.status; //statusobj
                return cansubmit;
              });

              if (submitarr.length === 0) {
                DeviceEventEmitter.emit('toast', {
                  message: '暂无可提交的日报记录！',
                  type: 'warning',
                });
                return;
              }

              const submitlogs = submitarr.map(it => {
                return {
                  id: it.id,
                  workTime: it.workTime,
                  projectId: it.projectId,
                  type: it.type,
                  remark: it.remark,
                };
              });

              let res = await dosubmit?.runAsync('/workTime', {
                workDate: selected,
                itemWorkTimeList: submitlogs,
              });
              if (res.code === 0) {
                DeviceEventEmitter.emit('toast', {
                  message: '提交成功!',
                  type: 'success',
                });
              }
            }}>
            {dosubmit?.loading ? (
              <ActivityIndicator color="#999999" />
            ) : (
              <FontAwesome
                name="paper-plane"
                size={16}
                color={Colors.primaryColor}
              />
            )}
          </TouchableOpacity>
        )}
      </View>
      <View style={{flex: 1}}>
        <Agenda
          ref={AgendaRef}
          id={'container'}
          items={state.items ?? {}}
          loadItemsForMonth={loadItems}
          selected={selected}
          renderEmptyDate={renderEmptyDate}
          rowHasChanged={(r1, r2) => {
            return r1.id !== r2.id;
          }}
          firstDay={0}
          minDate={'2023-10-1'}
          showClosingKnob={true}
          onDayPress={({dateString}) => {
            setSelected(dateString);
          }}
          // markingType={'period'}
          // monthFormat={'yyyy'}
          theme={{
            calendarBackground: Colors.backgroundColor,
            reservationsBackgroundColor: Colors.backgroundColor,
          }}
          markedDates={state.markedDates}
          renderList={listprops => {
            const dataSource = state?.items?.[selected] ?? [];

            if (dataSource.length === 0) {
              return (
                <View
                  padding-10
                  paddingH-16
                  margin-10
                  borderRadius={8}
                  row
                  centerV
                  gap={12}
                  backgroundColor={Colors.colorBgSecondary}>
                  <Image
                    source={require('../../assets/nodata.png')}
                    aspectRatio={1}
                    style={{
                      borderRadius: 8,
                      width: 66,
                      height: 66,
                      borderColor: Colors.colorCardBg,
                      overflow: 'hidden',
                      backgroundColor: 'transparent',
                      marginLeft: 0,
                    }}
                  />
                  <Text subheading flex-1>
                    暂无数据
                  </Text>
                </View>
              );
            }
            return (
              <FlatList
                style={{paddingBottom: 66, flex: 1}}
                data={dataSource}
                renderItem={({item}) => {
                  let it = item;
                  return ReportItem({
                    it,
                    navigation,
                    setAction,
                    state,
                    setState,
                  });
                }}
                keyExtractor={item => item.id.toString()}
                refreshControl={
                  <RefreshControl
                    refreshing={loading}
                    onRefresh={async () => {
                      return await runAsync({
                        workDateStart: dayjs(selected)
                          .startOf('month')
                          .format('YYYY-MM-DD'),
                        workDateEnd: dayjs(selected)
                          .endOf('month')
                          .format('YYYY-MM-DD'),
                      });
                    }}
                  />
                }
              />
            );
          }}
          // renderDay={renderDay}
          // showOnlySelectedDayItems
          // reservationsKeyExtractor={this.reservationsKeyExtractor}
        />
      </View>
    </View>
  );

  function loadItems(day) {
    const {dateString} = day;
    run({
      workDateStart: dayjs(dateString).startOf('month').format('YYYY-MM-DD'),
      workDateEnd: dayjs(dateString).endOf('month').format('YYYY-MM-DD'),
    });
  }

  function renderEmptyDate() {
    return (
      <View style={styles.emptyDate}>
        <Text>暂无数据!</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  item: {
    flex: 1,
    borderRadius: 5,
    padding: 10,
    marginRight: 10,
    marginTop: 17,
  },
  items: {
    borderRadius: 5,
    padding: 6,
    justifyContent: 'center',
    alignItems: 'center',
  },
  emptyDate: {
    height: 15,
    flex: 1,
    paddingTop: 36,
  },
  customDay: {
    margin: 10,
    fontSize: 24,
    color: 'green',
  },
  dayItem: {
    marginLeft: 34,
  },
});

export default memo(SubmitReport);
